﻿using CommunityToolkit.Mvvm.ComponentModel;
using ShanNiang.Service.Constants;
using ShanNiang.Service;
using CommunityToolkit.Mvvm.Input;
using ShanNiang.Service.Scaner;
using ShanNiang.Service.Interfaces;
using HandyControl.Controls;
using CommunityToolkit.Mvvm.Messaging;
using CommunityToolkit.Mvvm.Messaging.Messages;
using ShanNiang.Hosting.Enumerate;
using ShanNiang.Service.LoginModels.Requests;
using System.ComponentModel;
using Microsoft.Extensions.Logging;
using AutoMapper;
using ShanNiang.Mvvm.UiServices;

namespace ShanNiang.Mvvm.ViewModels
{
    public partial class LoginViewModel : ScannableViewModel, IRecipient<PropertyChangedMessage<bool>>
    {
        #region 服务注入
        private readonly UserContext _userContext;
        private readonly IIdsService _idsService;
        #endregion
        public LoginViewModel(
            BindViewModel bindViewModel,
            UserContext userContext,
            IIdsService idsService,
            PackingConfig packingConfig,
            IUiService uiService,
            IScanerService scanerService, IMapper mapper, ILogger<LoginViewModel> logger) : base(packingConfig, scanerService, uiService, mapper, logger)
        {
            _bindingViewModel = bindViewModel;
            _userContext = userContext;
            _idsService = idsService;
        }

        #region 字段和可观察属性
        /// <summary>
        /// 是否显示绑定空间，否则显示登陆Webview
        /// </summary>
        [ObservableProperty]
        private bool _bindPhoneNumber;
        /// <summary>
        /// 登陆Key
        /// </summary>
        [ObservableProperty]
        private Guid _loginKey;
        /// <summary>
        /// 登陆空间url
        /// </summary>
        [ObservableProperty]
        private string? _webViewUrl;
        /// <summary>
        /// 绑定空间的 viewModel
        /// </summary>
        [ObservableProperty]
        private BindViewModel _bindingViewModel;
        ///// <summary>
        ///// 浏览器空间
        ///// </summary>
        //public object? WebView2 { get; set; }
        #endregion

        #region 可绑定Command

        [RelayCommand]
        private async Task GetTokenAsync(WxLoginRequest request)
        {
            try
            {
                var remoteResponse = await _idsService.WxLoginAsync(request);

                if (remoteResponse != null && remoteResponse.Data != null)
                {
                    var resp = remoteResponse.Data;
                    _userContext.WxAppLoginResponse.Sign = resp.Sign;
                    _userContext.WxAppLoginResponse.ProviderKey = resp.ProviderKey;
                    _userContext.WxAppLoginResponse.LoginProvider = resp.LoginProvider;
                    if (remoteResponse.Code == GlobalErrorCode.Ok)
                    {
                        _userContext.WxAppLoginResponse.Success = true;
                        _userContext.WxAppLoginResponse.UserName = resp.UserName;
                        _userContext.Token = await _idsService.GetTokenAsync();
                        //给主窗口发消息，获取token成功
                        WeakReferenceMessenger.Default.Send(new PropertyChangedMessage<bool>(this, CommonData.GotToken, false, true));
                    }
                    else if (remoteResponse.Code == GlobalErrorCode.AccountUnBinding)
                    {
                        BindingViewModel.LoginKey = request.State;
                        BindPhoneNumber = true;
                    }
                }

            }
            catch (Exception ex)
            {
                Growl.Error(ex.Message);
            }
        }
        #endregion

        #region 重写、接口实现、事件处理
        protected override async Task LoadedAsync()
        {
            await base.LoadedAsync();
            if (!_userContext.WxAppLoginResponse.Success)
            {
                //没有登陆key   就去登陆
                if (string.IsNullOrEmpty(_userContext.WxAppLoginResponse.ProviderKey))
                {
                    ChangeToWebView2();
                }
                //有登陆key  就去绑定
                else
                {
                    ChangeToBindCtrl();
                }
            }
            else
            {

            }
        }


        protected override void OnPropertyChanged(PropertyChangedEventArgs e)
        {
            if (e.PropertyName == nameof(BindPhoneNumber))
            {
                IsActive = BindPhoneNumber;
            }
            base.OnPropertyChanged(e);
        }

        public void Receive(PropertyChangedMessage<bool> message)
        {
            if (message != null && message.PropertyName == CommonData.BindSuccess && message.NewValue)
            {
                ChangeToWebView2();
            }
        }

        protected override async Task CodeScanedAsync(object? sender, CodeEventArgs e)
        {
            Growl.Info(e.Code);
            await Task.CompletedTask;
        }
        #endregion

        #region 其他方法

        private void ChangeToWebView2()
        {
            BindPhoneNumber = false;
            LoginKey = Guid.NewGuid();
            WebViewUrl = $"{PackingConfig.IdentityServer}{CommonData.RedirectToWeChat}?loginKey={LoginKey}&channel=XkmWork";
        }

        private void ChangeToBindCtrl()
        {
            this.BindingViewModel.LoginKey = LoginKey.ToString();
            BindPhoneNumber = true;
        }

        #endregion
    }
}
